﻿using System.Text;
using RabbitMQ.Client;

namespace Sender
{
    /// <summary>
    /// 发布订阅模式
    /// </summary>
    public static class FanoutMode
    {
        public static void Run()
        {

            var factory = new ConnectionFactory()       // 创建连接工厂对象
            {
                HostName = "localhost",
                Port = 5672,
                UserName = "root",
                Password = "123456"
            };
            var connection = factory.CreateConnection();    // 创建连接对象
            var channel = connection.CreateModel();         // 创建连接会话对象

            #region 定义交换机
            string exchangeName = "exchange1";

            channel.ExchangeDeclare(exchange: exchangeName, type: ExchangeType.Fanout); // 把交换机设置为 fanout 发布订阅模式
            #endregion

            string str;
            do
            {
                Console.WriteLine("发送内容：");
                str = Console.ReadLine()!;

                byte[] body = Encoding.UTF8.GetBytes(str); // 消息内容

                channel.BasicPublish(exchangeName, "", null, body); // 发送消息
            } while (str.Trim().ToLower() != "exit");

            channel.Close();
            connection.Close();
        }
    }
}
